import 'dart:io';

import 'package:example/video_editor/video_editor_view_model.dart';
import 'package:example/video_player/video_trimmer_view.dart';

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:video_player/video_player.dart';

import 'package:zz_video_maker/zz_video_maker.dart';
import 'package:image_cropper/image_cropper.dart';

import '../components/time_slider.dart';
import '../components/video_component_widget.dart';

class VideoPlayerWidget extends StatefulWidget {
  const VideoPlayerWidget({super.key});

  @override
  State<VideoPlayerWidget> createState() => _VideoPlayerWidgetState();
}

class _VideoPlayerWidgetState extends State<VideoPlayerWidget> {
  VideoEditorViewModel get viewModel => Get.find<VideoEditorViewModel>();

  @override
  Widget build(BuildContext context) {
    return GetBuilder<VideoEditorViewModel>(
        id: 'playerView',
        builder: (viewModel) {
          double aspectRatio = 1;
          double width = MediaQuery.of(context).size.width;
          double height = MediaQuery.of(context).size.height;
          switch (viewModel.aspectRatio.value) {
            case ERatio.ratio169:
              aspectRatio = 16.0 / 9;
              break;
            case ERatio.ratio916:
              aspectRatio = 9.0 / 16;
            default:
              aspectRatio = 1;
          }

          return Stack(
            fit: StackFit.passthrough,
            children: [
              Container(
                alignment: Alignment.center,
                child: Stack(
                  children: [
                    AspectRatio(
                      aspectRatio: aspectRatio,
                      child: playerViewWidget(width, height),
                    ),
                    const Positioned(
                        bottom: 0, right: 0, left: 0, child: TimeSlider()),
                  ],
                ),
              ),
              trimmerWidget()
            ],
          );
        });
  }

  Widget playerViewWidget(double width, double height) {
    return GetBuilder<VideoEditorViewModel>(
        id: 'playerWidget',
        builder: (viewModel) {
          return GestureDetector(
            onTap: () {
              viewModel.allEditedData?.editingObject = null;
              viewModel.update(['component_widget']);

              if (viewModel.isPlaying) {
                viewModel.pause();
              } else {
                viewModel.play();
              }
            },
            child: Obx(
              () {
                EditedMedia editedMedia = viewModel.allEditedData!
                    .editedMediaList[viewModel.currentIndex.value];

                double scale =
                    width / viewModel.allEditedData!.resolution.minValue;

                return Stack(
                  fit: StackFit.expand,
                  children: [
                    Container(
                      color: Colors.black,
                      child: playerWidget(width, height),
                    ),
                    frameWidget(editedMedia, scale, width, height),
                    textsWidget(editedMedia, scale, width, height),
                    stickersWidget(editedMedia, scale, width, height),
                  ],
                );
              },
            ),
          );
        });
  }

  Widget playerWidget(double width, double height) {
    return GetBuilder<VideoEditorViewModel>(
      id: 'player',
      builder: (viewModel) {
        var con = viewModel.currentController();
        var data = viewModel.currentEditorData();
        var aspectRatio1 = data.mediaData.width / data.mediaData.height;
        return Stack(
          fit: StackFit.expand,
          children: [
            // ClipRect(
            //   child: Stack(
            //     children: [
            //       VideoPlayer(con),
            //       BackdropFilter(
            //         filter: ImageFilter.blur(sigmaX: 50, sigmaY: 50),
            //         child: Container(),
            //       ),
            //     ],
            //   ),
            // ),
            Container(
              alignment: Alignment.center,
              child: AspectRatio(
                aspectRatio: aspectRatio1,
                child: VideoPlayer(con),
              ),
            ),
          ],
        );
      },
    );
  }

  Widget frameWidget(
      EditedMedia editedMedia, double scale, double width, double height) {
    return GetBuilder<VideoEditorViewModel>(
      id: 'frame',
      builder: (controller) {
        var e = editedMedia.frame;
        var fileInfo = e?.fileMap[viewModel.aspectRatio.value];

        return fileInfo?.source.path == null
            ? const Text('Frame无图')
            : Image.file(
                File(fileInfo!.source.path!),
                fit: BoxFit.fill,
              );
      },
    );
  }

  Widget stickersWidget(
      EditedMedia editedMedia, double scale, double width, double height) {
    return GetBuilder<VideoEditorViewModel>(
      id: 'sticker',
      builder: (_) {
        return SizedBox(
          width: double.infinity,
          height: double.infinity,
          child: Stack(
            children: [
              ...editedMedia.stickers.map((e) {
                return VideoComponentWidget(
                  key: Key(e.hashCode.toString()),
                  data: e,
                  scale: scale,
                  child: e.fileInfo!.source.path == null
                      ? const Text('Sticker无图')
                      : Image.file(File(e.fileInfo!.source.path!)),
                );
              }),
            ],
          ),
        );
      },
    );
  }

  Widget textsWidget(
      EditedMedia editedMedia, double scale, double width, double height) {
    return GetBuilder<VideoEditorViewModel>(
      id: 'text',
      builder: (_) {
        return SizedBox(
          width: width,
          height: height,
          child: Stack(
            children: [
              ...editedMedia.editedTexts.map((e) {
                return VideoComponentWidget(
                  data: e,
                  scale: scale,
                  child: e.previewImagePath == null
                      ? Text(
                          e.text1 ?? e.text2 ?? '无图',
                          style: TextStyle(color: Colors.amber),
                        )
                      : Image.file(File(e.previewImagePath!)),
                );
              })
            ],
          ),
        );
      },
    );
  }

  Widget trimmerWidget() {
    return GetBuilder<VideoEditorViewModel>(
      id: 'trimmer',
      builder: (vm) {
        if (!vm.isTrimmerEditing) {
          return Container();
        }
        var editedMedia = vm.currentEditedMedia;
        if (editedMedia == null) {
          return Container();
        }

        return VideoTrimmerView(
          editedMedia: editedMedia,
          callback: () {
            vm.updateTrimmer(false, isUpdatePlayer: true);
          },
          cancel: () {
            vm.updateTrimmer(false);
          },
        );
      },
    );
  }
}
